import os
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

from model import UserRecord, UserSnapshot
from adapters import BaseAdapter
from adapters import *
import adapters

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>List of all users:<br/>')

        userRecords = db.GqlQuery("SELECT * "
        "FROM UserRecord "
        "ORDER BY date DESC LIMIT 100")

        if userRecords.count() == 0:
            self.response.out.write('noting found')
        else:
            for userRecord in userRecords:
                self.response.out.write('<a href="details?id={id}">{name}</a> <br/>'.format(id = userRecord.key().id(),
                                                                                            name = userRecord.user_name
                                                                                            ))

        self.response.out.write("""
        <br/>
        <a href="edit">Add new user</a>        
        </body>
        </html>""")

class Details(webapp.RequestHandler):
    def get_snapshot(self, userRecord):
        out = []
        for adapter in userRecord.adapters:
            out.append(
                    UserSnapshot.gql('WHERE parent=:userRecord and server=:adapter ORDER BY date DESC LIMIT 1',
                                     userRecord = userRecord, adapter = adapter)
                    )
        return out

    def get(self):
        userRecord = UserRecord.get_by_id( int( self.request.get('id') ) )
        self.response.out.write('<html><body>Details for {name}. <table>\n'.format(name =  userRecord.user_name ))
        for snap in self.get_snapshot(userRecord):
            self.response.out.write(
                    '<tr> <td>{server}</td> <td>{rating}</td> </tr>\n'
                    .format(server = snap.server, rating = snap.rating))
        self.response.out.write('<br/><a href="edit?id={id}">Edit</a>'.format(id = self.request.get('id') ))
        self.response.out.write('</table></body></html>')


class Editor(webapp.RequestHandler):
    def post(self):
    # toDo make security checks
        if self.request.get('id'):
            userRecord = UserRecord.get_or_insert( int(self.request.get('id')) )
        else:
            userRecord = UserRecord()
            userRecord.user_name = self.request.get('user_name')
            if users.get_current_user():
                userRecord.author = users.get_current_user()

        userRecord.adapters = self.request.get('adapter', allow_multiple=True)
        for adapter in userRecord.adapters:
            pass  # todo
            
        userRecord.put()
        self.redirect('/edit?id={id}'.format(id = userRecord.key().id() ))

    def get(self):
        if self.request.get('id'):
            userRecord = UserRecord.get_by_id( int( self.request.get('id') ))
            user_name = userRecord.user_name
        else:
            user_name = ''

        self.response.out.write("""<html><body>

        <form action="/edit" method="post">
            <div><input type="text" name="user_name" value="{user_name}"/></div>
            """.format(user_name = user_name) )

        for provider in adapters.__all__:
            module = globals()[ provider ]
            cls = module.__getattribute__(provider)
            obj = cls()
            self.response.out.write(
                    "<input type='checkbox' name='adapter' value='{server}'>{server}</input>: <br/>"
                    .format(server = obj.get_server() ) )
            for prop, title in obj.get_options().iteritems():
                self.response.out.write(
                        "{title}: <input type='text' value='{value}' name='{prop}'/> <br/>"
                        .format(value="", prop=prop, title=title) )
        self.response.out.write("""
            <div><input type="submit" value="Save"></div>
        </form>

        </body>
        </html>""")

application = webapp.WSGIApplication([
        ('/', MainPage),
        ('/details', Details),
        ('/edit', Editor)
        ], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
